<template>
    <el-row>
        <el-col :span="24" style="padding: 24px;">
            <el-button @click="openDialog(false)" icon="Plus" type="primary">新建资金账户</el-button>
            <el-button icon="Refresh" @click="refreshList">刷新列表</el-button>
        </el-col>
    </el-row>

    <el-row>
        <el-col :span="24" style="padding:12px; min-height: 400px; height: 70vh;">
            <!-- 设置表格最大高度，超出出现滚动条 宽度自适应父容器-->
            <el-table v-loading="loading" :data="fundAccountList" style="width: 100%; min-width: 800px; height: 100%;">
                <el-table-column label="账户名称" align="center" prop="name"></el-table-column>
                <el-table-column label="余额" align="center" prop="balance"></el-table-column>
                <el-table-column label="收入总额" align="center" prop="income"></el-table-column>
                <el-table-column label="支出总额" align="center" prop="expenses"></el-table-column>
                <el-table-column v-if="showStoreOption" label="所属门店" align="center">
                    <template #default="scope">
                        {{ scope.row.store ? scope.row.store.name : '无' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="300" align="center" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-link :underline="false" style="margin-left: 24px;" type="primary"
                            @click="openDialog(true, scope.row)">编辑</el-link>
                        <el-link :underline="false" style="margin-left: 24px;" type="primary"
                            @click="action(scope.row, 'del')">删除</el-link>
                    </template>
                </el-table-column>
            </el-table>
        </el-col>
    </el-row>

    <div style="width: 50%; min-width: 400px; margin: 0 auto; padding: 0;">
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />
    </div>

    <!-- 新建/编辑资金账户弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '资金账户编辑' : '新建资金账户'" width="500" draggable align-center
        :before-close="handleCloseDialog">
        <div>
            <el-form ref="fundAccountFormRef" label-suffix=":" :model="formData" :rules="formRules" label-width="120px"
                style="max-width: 600px">
                <el-form-item label="账户编号" prop="accountCode">
                    <el-input v-model="formData.accountCode" />
                </el-form-item>                
                <el-form-item label="账户名称" prop="name">
                    <el-input v-model="formData.name" />
                </el-form-item>
                <el-form-item label="银行账户名" prop="bankAccountName">
                    <el-input v-model="formData.bankAccountName" />
                </el-form-item>
                <el-form-item label="开户行" prop="bankName">
                    <el-input v-model="formData.bankName" />
                </el-form-item>
                <el-form-item label="账户号码" prop="accountNo">
                    <el-input v-model="formData.accountNo" />
                </el-form-item>
                <el-form-item  v-if="showStoreOption"  label="所属门店" prop="store">
                    <el-select v-model="formData.store" placeholder="请选择门店" clearable>
                        <el-option v-for="store in storeList" :key="store.id" :label="store.name" :value="store">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="formData.remark" type="textarea" />
                </el-form-item>
                <el-form-item v-if="!isEdit" label="初始余额" prop="balance">
                    <el-input-number v-model="formData.balance" :precision="2" :step="100" />
                </el-form-item>
            </el-form>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="submitForm" type="primary" :loading="submitLoading">
                    提交
                </el-button>
                <el-button @click="handleCloseDialog" :disabled="submitLoading">
                    取消
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { FundUiAction } from '../../public/engine/uiAction/fundUiAction'
import { Definition } from '../../public/engine/common/definition'
import { DataPage } from '../../public/network/communicationConverter'
import { Engine } from '../../public/engine/engine.js'
import { FundAccount,FundAccountFilter } from '../../public/engine/funds/fundAccount.js'
import { deleteFundAccountListNetworkCacheData } from '../../public/network/api.js'
import {FundAccountInsideType} from '../../public/engine/common/fundDefinition';

export default {
    name: 'FundAccountMgtPage',
    data() {
        return {
            total: 0,
            loading: false,
            queryParams: {
                pageNum: 1,
                pageSize: Definition.gDefualPageSize,
            },
            fundAccountList: [],
            storeList: [],
            dialogVisible: false,
            isEdit: false,
            submitLoading: false,
            fundAccountFormRef: null,
            formData: {
                id: '',
                name: '',
                accountCode: '',
                bankAccountName: '',
                bankName: '',
                accountNo: '',
                store: null,
                remark: '',
                balance: 0
            },
            formRules: {
                name: [
                    { required: true, message: '请输入账户名称', trigger: 'blur' }
                ],                
            },
            fundUiAction: new FundUiAction(),
            filter: new FundAccountFilter({accountInsideType : FundAccountInsideType.NormalAccount})
        }
    },

    computed: {
        showStoreOption() {
            return (Engine.getOrgSettings().multiStoreMode ||
                Engine.getOrgSettings().forceToShowOrderStoreInfo);
        }
    },

    methods: {
        refreshList() {
            deleteFundAccountListNetworkCacheData();
            this.getList();
        },

        async getList() {
            try {
                this.loading = true
                const res = await this.fundUiAction.getFundAccountData({
                    pageInfo: new DataPage(this.queryParams.pageNum, 0, this.queryParams.pageSize),
                    filter:this.filter
                })

                if (res && res.data && res.data.dataList) {
                    this.fundAccountList = res.data.dataList
                    this.total = res.data.pageInfo.total;
                } else if (res.resErr) {
                    console.error('获取列表失败', res.resErr)
                    ElMessage.error('获取列表失败')
                }
            } catch (error) {
                console.error('获取列表失败', error)
                ElMessage.error('获取列表失败')
            } finally {
                this.loading = false
            }
        },

        openDialog(editMode = false, rowData = null) {
            this.isEdit = editMode
            if (editMode && rowData) {
                // Clone the row data to avoid modifying the original
                this.formData = {
                    id: rowData.id,
                    name: rowData.name,
                    accountCode: rowData.accountCode,
                    bankAccountName: rowData.bankAccountName,
                    bankName: rowData.bankName,
                    accountNo: rowData.accountNo,
                    store: rowData.store,
                    remark: rowData.remark,
                    balance: rowData.balance
                }
            } else {
                this.resetForm()
            }
            this.dialogVisible = true
        },

        resetForm() {
            this.formData = {
                id: '',
                name: '',
                accountCode: '',
                bankAccountName: '',
                bankName: '',
                accountNo: '',
                store: null,
                remark: '',
                balance: 0
            }
            if (this.$refs.fundAccountFormRef) {
                this.$refs.fundAccountFormRef.resetFields()
            }
        },

        handleCloseDialog() {
            if (!this.submitLoading) {
                this.dialogVisible = false
            }
        },

        async submitForm() {
            try {
                this.submitLoading = true
                await this.$refs.fundAccountFormRef.validate()

                // Create FundAccount object from form data
                const fundAccount = new FundAccount({
                    id: this.formData.id,
                    name: this.formData.name,
                    accountCode: this.formData.accountCode,
                    bankAccountName: this.formData.bankAccountName,
                    bankName: this.formData.bankName,
                    accountNo: this.formData.accountNo,
                    store: this.formData.store,
                    remark: this.formData.remark,
                    balance: this.formData.balance
                });

                const apiResult = await this.fundUiAction.updateOrCreateFundAccount(fundAccount, false);

                if (apiResult && apiResult.resErr == null) {
                    ElMessage.success(this.isEdit ? '编辑成功' : '创建成功')
                    this.dialogVisible = false;
                    this.getList()
                } else {
                    ElMessage.error((this.isEdit ? '更新失败' : '新增失败:') + (apiResult ? apiResult.resErr : '未知错误'))
                }
            } catch (error) {
                console.error('提交失败', error)
                if (error !== 'validate') {
                    ElMessage.error('提交失败')
                }
            } finally {
                this.submitLoading = false
            }
        },

        async delFundAccountRecord(id) {
            try {
                await ElMessageBox.confirm('确认删除此资金账户? 此操作不可恢复', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                const res = await this.fundUiAction.removeFundAccount(id)
                if (res && res.resErr) {
                    ElMessage.error('删除失败:' + res.resErr);
                } else {
                    ElMessage.success('删除成功')
                    this.getList()
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除失败', error)
                    ElMessage.error('删除失败')
                }
            }
        },

        action(data, type) {
            if (type === 'del') {
                this.delFundAccountRecord(data.id)
            }
        },

        resetQuery() {
            this.queryParams.page = 1
            nextTick(() => {
                this.getList()
            })
        },

        // Load store list for dropdown
        loadStoreList() {
            // In a real implementation, this would fetch stores from the backend
            // For now, we can use the engine's profile stores if available
            if (Engine.profile && Engine.profile.storeList) {
                this.storeList = Engine.profile.storeList;
            }
        }
    },

    mounted() {
        this.loadStoreList();
        this.getList()
    }
}
</script>